package com.grm.util;

import com.grm.constant.UserConstant;
import com.grm.exception.BusinessException;
import io.jsonwebtoken.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * jwt工具类
 */
@Data
@Component
@Slf4j
public class JwtUtil {
    @Value("${password.salt}")
    private String salt;

    public String createToken(String username) {
        JwtBuilder jwtBuilder = Jwts.builder().setSubject(username)  //设置主题 Jwt面向的用户
            .claim("username", username) //自定义属性
            .claim("uuid", UUIDUtil.get32UUID())
            .signWith(SignatureAlgorithm.HS256, salt);//签名,进行**加密
        return jwtBuilder.compact();
    }

    /**
     * 解析token
     *
     * @param token
     * @return
     */
    public String parseToken(String token) {
        try {
            Claims body = (Claims)Jwts.parser().setSigningKey(salt).parse(token).getBody();
            return String.valueOf(body.get("username"));
        } catch (ExpiredJwtException | MalformedJwtException | SignatureException | IllegalArgumentException e) {
            throw new BusinessException(UserConstant.UN_LOGIN,"非法token！");
        }
    }
}
